$(function () {
    var query = {}, fields = 'id|userName|password|name|gender|phone',
        $search = $('.search'), $searchBar = $('.search-btn');
    var config = {
        coloum_num: 8, //列数目
        query: '/order/query?',//分页查询URL,
        get_print: '/order/print',//分页查询URL,
        create: '/order/create',//create,
        update: '/order/update',
        payed: '/order/payed',
        force_end: '/order/forceEnd',
        check: '/order/checkStatus',
        update_actual_price: '/order/updatePrice',
        create_labing_bill: '/ladingBill/create',
        'delete': '/order/delete',
    };
    $searchBar.click(function () {
        $(this).button('loading');
        console.log({keyword: $search.val()});
        search({keyword: $search.val()});
    });
    /***
     *
     * @param obj
     * @returns {*|{opacity}}
     */
    function search(obj) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        var arg = [];
        if (isSameQueryStr(query_,query)) { //查询条件和上次一样，取消请求
            $searchBar.button('reset');
            return $loading.fadeOut();
        }
        Object.keys(query_).map(function (key) {
            arg.push(key + '=' + query_[key])
        });
        arg.push('checkStatus=1');
        query = query_;query.timestamp = Date.now(); 
        $.get(config.query + ajaxArgStrGenerator(query), function (res) {
            $searchBar.button('reset');
            if (res.list.length) {
                render(res.list)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                    $searchBar.click();
                })
            }
            var page = res.page;
            pageInit(page,query,search);

        });
    }

    function render(list) {
        $('.table-responsive .table tbody').html('');
        if (list instanceof Array) {
            list.forEach(function (item, index) {
                // re
                $('.table-responsive .table tbody')
                    .append('<tr> \
                    <td scope="row">' + (index + 1) + ' \
                </td> \
                <td>' + item.no + '</td> \
                <td>' + (item.clienteleName) + '</td> \
                <td>' + (item.clienteleUserName) + '</td> \
                <td>' + (item.clienteleUserPhone) + '</td> \
                <td>' + item.goodsName + '</td> \
                <td class="text-right">' + number_format(item.actualPrice,2) + '</td> \
                <td class="text-right">' + number_format(item.number,3) + '</td> \
                <td class="text-right">' + number_format(item.actualTotal,2) + '</td> \
                <td class="text-right">' + number_format(item.deliverNumber,3) + '</td> \
                <td>' + (item.payStatus == 0 ? '未付款' : '已付款') + '/' + (item.checkStatus == 0 ? '未审核' : (item.checkStatus == 1 ? '<span class="label label-success">审核通过</span>' : (item.checkStatus == 2 ? '<span class="label label-danger">拒绝</span>' : ''))) + '</td> \
                <td>' + orderStatus(item.status).text + '</td> \
                <td>' + orderPayMethod(item.payMethod).text + '</td> \
                <td>' + moment(item.payDate).format('YYYY-MM-DD') + '</td> \
                <td>' + (item.payCondition||'') + '</td> \
                <td>' + item.saleName + '</td> \
                <td class="text-right" style="width: 37px;"> \
                    <div class="btn-group" role="group" style="position: relative;width:37px;">' +
                        ((item.checkStatus == 0 && item.status == 0) ? '<button type="button" class="btn btn-xs  btn-primary interactive opt-check" data-toggle="modal" data-target=" .order-check"  data-json=\'' + JSON.stringify(item) + '\' >审核</button>' : '') +
                        '<div class="operate-area" style="right:2px;">' +
                        '<a href="./order-detail.html?id=' + item.id + '" class="btn btn-xs  btn-primary" >查看</a>' +
                        ((item.payStatus == 0 && item.status == 0) ? '<button type="button" data-id="' + item.id + '" class="btn btn-xs btn-danger opt-pay">收款</button>' : '') +
                        '</div><button type="button" class="btn btn-xs btn-primary opt-detail operate-detail">更多</button>' +
                        '</div></td></tr>');
            });

            $('.opt-pay').click(function () {
                if (confirm('确认已经收款?')) {
                    $.post('/order/payed', {id: $(this).data('id')}, function (xhr) {
                        if (xhr.code == 200) {
                            alert("收款成功!");
                            search({},true);
                        } else {
                            alert(xhr.error);
                        }
                    })
                }
            });
            $('.opt-order-end').click(function () {
                if (confirm('确定终止此订单执行?!')) {
                    $.post(config.update, {id: $(this).data('id'), status: '1'}, function (data) {
                        if (data.code == 200) {
                            search({},true);
                        } else {
                            alert(xhr.error);
                        }
                    })
                }
            });
            $('.opt-order-force-end').click(function () {
                if (confirm('确定终止此订单执行?!')) {
                    $.post(config.force_end, {id: $(this).data('id'), status: '3'}, function (data) {
                        if (data.code == 200) {
                            alert('执行成功!')
                            search({},true);
                        } else {
                            alert(data.error);
                        }
                    })
                }
            });
            $('.opt-detail').click(function () {
                var self = this;
                $(this).siblings('.operate-area').toggle();
            });

            $('.opt-update').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var item = $(this).data('json');
                fields.split('|').map(function (key) {
                    var $item = $('[name=' + key + ']');
                    if ($item[0].type == 'radio') {
                        $('[name=' + key + '][value=' + item[key] + ']').attr('checked', true)
                    } else {
                        $item.val(item[key]);
                    }
                });
            });
            $('.opt-print').click(function () {
                $.get(config.get_print + '?id=' + $(this).data('id'), function (data) {
                    $.alert({
                        title: '打印合同',
                        okbtn: '打印',
                        width: $(window).width() - 300,
                        body: data.error,
                        okHide: function (e) {

                            $('#contract').jqprint();
                            return false;
                        }
                    })
                })
            });
            /***
             * 修改订单
             */
            $('.opt-order-update').click(function (d) {
                var self = this;
                var item = $(self).data('json');
                var $alertUpdateActualPrice = $.alert({
                    title: '修改订单',
                    hasfoot: false,
                    width: 'normal',
                    body: $('#actual-price-template').html(),
                    shown: function () {
                        var btnUpdateActualPrice = $('.btn-update-actual-price');
                        $('[name=actualPrice]').val(item.actualPrice);
                        $(".form-update-actual-price").validate({
                            submitHandler: function (form_) {
                                btnUpdateActualPrice.button('loading');
                                var form = {};
                                'actualPrice'.split('|').map(function (item) {
                                    form[item] = form_[item].value
                                });
                                form['id'] = item.id;
                                $.post(config.update_actual_price, form, function (xhr, data) {
                                    if (xhr.code == 200) {
                                        search({},true);
                                        $alertUpdateActualPrice.modal('hide');
                                    } else {
                                        alert(xhr.error)
                                    }
                                    btnUpdateActualPrice.button('reset');
                                });
                                return false;
                            }
                        });
                    },
                })
            });
            $('.opt-send').click(function () {
                var ladingBillFields = 'type|carId|driver|driverPhone|numberThisTime|expireTime';
                var self = this;
                var $alertCreateLabingBill = $.alert({
                    title: '发货申请',
                    hasfoot: false,
                    width: 'normal',
                    body: $('#lading-bill-template').html(),
                    shown: function () {
                        $("[name=expireTime]").datepicker({
                            todayHighlight: true,
                            startDate: formatDate(new Date())
                        });
                        var btnCreateLadingBill = $('.btn-create-lading-bill');

                        $(".create-lading-bill").validate({
                            submitHandler: function (form_) {
                                btnCreateLadingBill.button('loading');
                                var form = {};
                                ladingBillFields.split('|').map(function (item) {
                                    form[item] = form_[item].value
                                });
                                form['orderId'] = $(self).data('id');
                                $.post(config.create_labing_bill, form, function (xhr, data) {
                                    if (xhr.code == 200) {
                                        search({},true);
                                        $alertCreateLabingBill.modal('hide');
                                    } else {
                                        alert(xhr.error)
                                    }
                                    btnCreateLadingBill.button('reset');
                                });
                                return false;
                            }
                        });
                    },
                })
                // $.get(config.get_print + '?id=' + $(this).data('id'), function (data) {
                //
                // })
            });
            $('.opt-delete').click(function () {
                $(this).closest('tr').addClass('active').siblings('tr').removeClass('active');
                var self = this;
                $(this).button('loading');

                var item = $(this).data('json');
                if (confirm('确认删除？')) {
                    $.post(config.delete, {id: item.id}, function (xhr, data) {
                        $(self).button('reset');
                        $(self).closest('tr').remove()
                    });
                } else {
                    $(self).button('reset');
                }
            });
        } else {
            $('.table-responsive .table tbody').html(list);
        }
        $loading.fadeOut();
    }

    search({},true);
    $('.order-check').on('show', function (event) {
        var button = $(event.relatedTarget);
        var recipient = button.data('json');
        console.log(recipient);
        var modal = $(this);
        modal.find('.modal-title').text('审核订单');
        modal.find('.modal-title').data('id', recipient.id);
    }).on('okHide', function (event) {
        var $id = $(event.target).closest('.modal-content').find('.modal-title').data('id');
        if ($(event.target).text().indexOf('通过') > -1) {
            $.post(config.check, {
                id: $id,
                checkStatus: 1,
            }, function (data) {
                if (data.code == 200) {
                    search({},true);
                    $('.order-check').modal('hide');
                } else {
                    alert(data.error)
                }
            })
        } else if ($(event.target).text().indexOf('拒绝') > -1) {
            var $refuse = $('.hp-refuse');
            if (!$refuse.val()) {
                return $refuse.addClass('hp-input-error')
            } else {
                $refuse.removeClass('hp-input-error');
            }
            $.post(config.check, {
                id: $id,
                checkStatus: 2,
                reason: $refuse.val()
            }, function (data) {
                if (data.code == 200) {
                    search({},true);
                    $('.order-check').modal('hide');
                } else {
                    alert(data.error)
                }
            })
        }
        return false;
    });
    // Button that triggered the modal var recipient = button.data('whatever') // Extract info from data-* attributes // If necessary, you could initiate an AJAX request here (and then do the updating in a callback). // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead. var modal = $(this) modal.find('.modal-title').text('New message to ' + recipient) modal.find('.modal-body input').val(recipient) })


    // 表单提交
    var $submit = $('#submit');
    $submit.on('click', function () {
        var $btn = $(this).button('loading');
    });

    $("#user-form").validate({
        submitHandler: function (form_) {
            var form = {};
            fields.split('|').map(function (item) {
                form[item] = form_[item].value
            });
            var url = config.create;
            if (form.id) { // is update?
                url = config.update;
            } else {
                delete form.id;
            }
            $.post(url, form, function (xhr, data) {
                $submit.button('reset');
            });
            return false;
        }
    });
    $('.table th .fa').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};
        sort.sortField = $(this).data('sort');
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search(sort);
    })
});